<!--
 * @Des: 字典管理
 * @Author: jin_yc
 * @Date: 2019-11-08 10:21:45
 * @LastEditor: jin_yc
 * @LastEditTime: 2021-12-28 19:23:23
 -->

<template>
  <div class="dic">
    <fks-row style="height: 100%">
      <fks-col :span="12" style="height: 100%">
        <fks-query-page
          v-loading="loading"
          :data="tableData"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[20, 50, 100]"
          highlight-current-row
          :page-size.sync="pageSize"
          :current-page.sync="currentPage"
          :total="total"
          :element-loading-text="LANG.LOADING"
          :table-name="LANG.SYS_DICTIONARY"
          @query="initData"
        >
          <template slot="singleSearch">
            <div class="single-searchBox">
              <fks-input
                v-model="searchValue"
                size
                :placeholder="LANG.NAME_CODE"
                class="single-searchBox-item"
                clearable
                maxlength="50"
                @clear="search"
                @keyup.enter.native="search"
              >
                <fks-button
                  slot="append"
                  icon="fks-icon-search"
                  @click="search"
                />
              </fks-input>
              <span>
                <fks-button
                  v-if="developerModeShow == 1"
                  icon="fks-icon-plus"
                  type="primary"
                  @click="add"
                >
                  <span>{{ LANG.ADD }}</span>
                </fks-button>
              </span>
            </div>
          </template>
          <template>
            <fks-table-column type="index" align="center" label="#" />
            <fks-table-column
              prop="code"
              :label="LANG.DICTIONARY_KEY"
              align="left"
              header-align="center"
              min-width="120px"
              is-link
              @link="getDicDetail"
            />
            <fks-table-column
              prop="content"
              :label="LANG.DICTIONARY_NAME"
              align="left"
              header-align="center"
              min-width="120px"
            />
            <!-- 暂时去掉排序 -->
            <!-- <fks-table-column
              prop="content"
              :label="LANG.DICTIONARY_NAME"
              align="left"
              sortable="custom"
              header-align="center"
              isLink
              min-width="80px"
              @link="getDicDetail"
            >
            </fks-table-column> -->

            <!-- <fks-table-column
              prop="type"
              :render-header="langSelects"
              header-row-class-name="select-lang"
              align="center"
              min-width="80px"
            >
              <template slot-scope="scope">
                {{ scope.row.type | transferEnum('modules') }}
              </template>
            </fks-table-column> -->
            <fks-table-column
              v-if="developerModeShow == 1"
              :label="LANG.OPERATION"
              class-name="table-opt-colunm"
              width="100"
              align="left"
            >
              <template slot-scope="scope">
                <fks-button
                  class="table-column-opt-button"
                  type="text"
                  @click="edit(scope.row)"
                >
                  {{ LANG.EDIT }}
                </fks-button>
                <fks-button danger-text @click="deleteRow(scope.row)">
                  {{ LANG.DELETE }}
                </fks-button>
              </template>
            </fks-table-column>
          </template>
        </fks-query-page>
      </fks-col>
      <fks-col :span="12" style="height: 100%">
        <div class="dic-detail-box">
          <fks-query-page
            v-loading="detailLoading"
            :data="detailTableData"
            :element-loading-text="LANG.LOADING"
            :table-name="dictName ? `${dictName} - ${LANG.DICTIONARY_DETAIL}`: LANG.DICTIONARY_DETAIL"
            row-key="id"
            :page="false"
            default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <template slot="singleSearch">
              <div class="single-searchBox">
                <span v-if="developerModeShow == 1">
                  <fks-button
                    icon="fks-icon-plus"
                    type="primary"
                    @click="addDetail"
                  >
                    <span>{{ LANG.ADD }}</span>
                  </fks-button>
                </span>
              </div>
            </template>
            <template>
              <fks-table-column
                type="index"
                align="center"
                label="#"
                width="50"
              />
              <fks-table-column
                :label="LANG.DICCODE"
                align="left"
                header-align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  {{ scope.row.content.code }}
                </template>
              </fks-table-column>
              <fks-table-column
                v-if="languages.length > 0"
                :render-header="langSelect"
                header-row-class-name="select-lang"
                align="left"
                header-align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  {{ scope.row.content.content }}
                </template>
              </fks-table-column>
              <fks-table-column
                v-if="languages.length == 0"
                :label="defaultLabel"
                align="left"
                header-align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  {{ scope.row.content.content }}
                </template>
              </fks-table-column>
              <fks-table-column
                v-if="developerModeShow == 1"
                :label="LANG.OPERATION"
                width="200"
                align="left"
              >
                <template slot-scope="scope">
                  <fks-button type="text" @click="addSubDetail(scope.row)">
                    {{ LANG.ADD_SUBDIC }}
                  </fks-button>
                  <fks-button type="text" @click="editDetail(scope.row)">
                    {{ LANG.EDIT }}
                  </fks-button>
                  <fks-button danger-text @click="deleteRow(scope.row)">
                    {{ LANG.DELETE }}
                  </fks-button>
                </template>
              </fks-table-column>
            </template>
          </fks-query-page>
        </div>
      </fks-col>
    </fks-row>
    <dic-dialog
      :dialog-type="dialogType"
      :data.sync="dicData"
      :visible="dialogVisible"
      @close="dialogVisible = false"
    />
    <dragtable
      :data="detailNode"
      :visible.sync="detailDialogVisible"
      :type="type"
    />
  </div>
</template>

<script>
import DicDialog from './DictDeatil/DicDialog'
import Dragtable from './DictDeatil/Dragtable'
import {
  getDic,
  getDicDetail,
  deleteDic,
  deleteDicDetail,
  getAllDicDetail,
  sort,
  getLangDicDetail
} from '../api'
import { ENUM } from '@/store/State/stateTypes'
// import Sortable from 'sortablejs'
import { lang } from '@/modules/SysConfig/Lang/langClass.js'
export default {
  name: 'SystemDict',
  components: {
    DicDialog,
    Dragtable
  },
  data() {
    return {
      loading: false,
      detailLoading: false,
      searchValue: '',
      dialogVisible: false,
      detailDialogVisible: false,
      dialogType: '',
      // detailTotal: 0,
      type: 'add',
      detailNode: {}, //新增字典详情的时候传递给组件的对象
      detailTableData: [],
      selectList: [],
      defaultLabel: '',
      currentType: '',
      currentPage: 1,
      id: '',
      dictionaryId: '', //当前字典id（左侧选中字典）
      dictName: '', //字典名称，右侧列表标题
      pathId: '', //字典
      sort: '',
      sortValue: '',
      pageSize: 20,
      total: 0,
      currentLang: '', //字典详情表表头中所选语种
      dicData: {},
      tableData: [],
      developerModeShow: 0,
      subParentId: '' //新增字典子节点时，保存父节点的id
    }
  },
  computed: {
    lang() {
      return this.$lang
    },
    languages() {
      return this.$store.state[ENUM].languages || []
    }
  },
  watch: {
    dictName(val) {
      if (val && val.length > 20) {
        this.dictName = val.slice(0, 20) + '...'
      }
    },
    //监听语种切换
    currentLang(val) {
      this.detailLoading = true
      let data = {
        parentId: this.dictionaryId,
        langCode: val
      }
      this.getDicDetailData(data)
    },
    currentType(val) {
      let data = {
        page: this.currentPage,
        size: this.pageSize,
        serviceType: '0'
      }
      this.loading = true
      this.detailLoading = true
      if (val != 'ALL') {
        data.type = val
        this.getDicList(data)
      }
      this.getDicList(data)
    },
    $lang(val) {
      if (this.languages.length > 0) {
        this.languages.forEach((item) => {
          if (item.code == val) {
            this.currentLang = item.code
            //this.selectList = []
            this.initData()
          }
        })
      }
    }
  },
  mounted() {
    lang.forEach((item) => {
      if (item.code === this.$lang) {
        this.defaultLabel = item.name
      }
    })
  },
  created() {
    this.developerModeShow = sessionStorage.getItem('developerMode')
    this.initData()
  },
  methods: {
    //字典详情列表添加子节点
    addSubDetail(row) {
      this.pathId = row.content.pathId //储存父节点pathId
      this.subParentId = row.id //储存父节点parentId
      this.addDetail('addSub')
    },
    //字典列表数据排序
    sortHandler(data) {
      let params = {}
      if (!data.order) {
        this.sort = ''
        this.sortValue = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
        this.sortValue = data.prop
      }
      params = {
        page: this.currentPage,
        size: this.pageSize,
        name: this.searchValue,
        serviceType: 0,
        type: this.currentType == 'ALL' ? '' : this.currentType,
        sort: this.sort,
        sortValue: this.sortValue
      }
      this.getDicList(params)
    },

    //字典详情数据排序后保存方法
    saveDetail() {
      sort(this.detailTableData).then((res) => {
        if (res.status) {
          this.$message.success(this.LANG.CHANGE_SORT_SUCCESS)
        }
      })
    },
    langSelects(h, { column, $index }) {
      // 给表格添加包裹的div
      return h('div', {}, [
        // 添加el-select 标签
        h(
          'fks-select',
          {
            on: {
              input: (value) => {
                this.currentType = value
              }
            },
            props: {
              value: this.currentType, // 给el-select 设置值（也是相当于v-model）
              size: 'small',
              class: 'select-lang',
              style: {
                height: '25px',
                width: '110px',
                paddingLeft: '0px',
                paddingRight: '0px'
              }
            }
          },
          [
            //给当前 el-select 设置 el-option
            this.selectList.map((item) => {
              return h('fks-option', {
                props: {
                  value: item.value,
                  label: item.label
                }
              })
            })
          ]
        )
      ])
    },
    langSelect(h, { column, $index }) {
      // 给表格添加包裹的div
      return h('div', {}, [
        // 添加el-select 标签
        h(
          'fks-select',
          {
            on: {
              input: (value) => {
                this.currentLang = value
              }
            },
            props: {
              value: this.currentLang, // 给el-select 设置值（也是相当于v-model）
              size: 'small',
              class: 'select-lang',
              style: {
                height: '25px',
                width: '110px',
                paddingLeft: '0px',
                paddingRight: '0px'
              }
            }
          },
          [
            //给当前 el-select 设置 el-option
            this.languages.map((item) => {
              return h('fks-option', {
                props: {
                  value: item.code,
                  label: item.name
                }
              })
            })
          ]
        )
      ])
    },
    //删除字典详情
    deleteRow(row) {
      this.$confirm(this.LANG.DELETE_CONFIRM, {
        title: this.LANG.TIPS,
        type: 'warning',
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      }).then(() => {
        //删除左侧列表 根节点
        deleteDic(row.id).then((res) => {
          if (res.status) {
            this.currentPage = 1
            if (row.content.hasOwnProperty('sort')) {
              let data = {
                parentId: this.dictionaryId,
                langCode:
                  this.languages.length > 0 ? this.currentLang : this.$lang
              }
              this.getDicDetailData(data) //查询第一个字典详情
            } else {
              this.initData()
            }
            this.$message.success(this.LANG.DELETE_SUCCESS)
          }
        })
        // if (row.hasOwnProperty('sort')) {
        //   deleteDicDetail({ id: row.parentId, code: row.code }).then((res) => {
        //     if (res.status) {
        //       this.$message.success(this.LANG.DELETE_SUCCESS)
        //       this.updateDicDetail()
        //     }
        //   })
        // } else {
        //   deleteDic(row.id).then((res) => {
        //     if (res.status) {
        //       this.currentPage = 1
        //       this.getDefaultData()
        //       this.$message.success(this.LANG.DELETE_SUCCESS)
        //     }
        //   })
        // }
      })
    },
    //打开新增字典详情弹窗
    addDetail(type) {
      this.detailDialogVisible = true
      this.type = 'add'
      let langCode = ''
      let langName = ''
      //若所配置的国际化语种中，有当前表格头所选语种
      if (this.languages.length > 0) {
        this.languages.forEach((item) => {
          if (item.code == this.currentLang) {
            langCode = item.code
            langName = item.name
          }
        })
      }
      this.detailNode = {
        langName: langName,
        langCode: langCode,
        parentId: type == 'addSub' ? this.subParentId : this.dictionaryId,
        pathId: this.pathId,
        serviceType: 0,
        dictionaryId: this.dictionaryId
        // detailTotal: this.detailTotal
      }
    },
    //打开编辑字典详情弹窗
    async editDetail(row) {
      let pId = []
      let langCode = ''
      let langName = ''
      this.detailDialogVisible = true
      this.type = 'edit'
      //编辑时获取所有翻译
      await getAllDicDetail({
        dictionaryId: row.id,
        langCode: ''
      }).then((res) => {
        res.data.forEach((item) => {
          if (item.content) {
            // if (item.langValue != row.langCode) {
            row[item.langCode] = item.content
            // }
          }
          pId.push({ id: item.id, label: item.langCode })
        })
        if (this.languages.length > 0) {
          this.languages.forEach((item) => {
            if (item.code == this.currentLang) {
              langCode = item.code
              langName = item.name
            }
          })
        }
        Object.assign(
          row,
          {
            langCode: this.languages.length > 0 ? langCode : this.$lang,
            langName: langName
          },
          {
            pId: pId,
            code: row.content.code,
            dictionaryId: this.dictionaryId,
            sort: row.content.sort
          }
        )
        this.detailNode = JSON.parse(JSON.stringify(row))
      })
    },
    //清空搜索值回调
    search() {
      this.currentPage = 1
      this.tableData = []
      // this.getDefaultData()
      this.initData()
    },
    /**
     * @description: 初始化的时候获取字典、字典详情数据
     */
    getDefaultData() {
      this.detailTableData = []
      this.tableData = []
      this.loading = true
      this.detailLoading = true
      const data = {
        page: this.currentPage,
        size: this.pageSize,
        serviceType: '0',
        name: this.searchValue,
        type: this.currentType == 'ALL' ? '' : this.currentType,
        sort: this.sort,
        sortValue: this.sortValue
      }
      this.getDicList(data)
    },
    getDicList(data) {
      getDic(data)
        .then((res) => {
          this.loading = false
          if (res.status) {
            this.tableData = res.data.list
            this.total = res.data.total
            if (res.data.list[0]) {
              this.dictName = res.data.list[0]?.content
              this.id = res.data.list[0].id
              let data = {
                id: this.id,
                langCode:
                  this.languages.length > 0 ? this.currentLang : this.$lang,
                page: 1,
                size: 9999
              }
              this.getDicDetailData(data)
            } else {
              this.detailLoading = false
            }
          } else {
            this.detailLoading = false
          }
        })
        .catch(() => {
          this.loading = false
          this.detailLoading = false
        })
    },
    //点击字典名称获取字典下字典详情数据
    getDicDetail({ row }) {
      this.detailLoading = true
      this.dictionaryId = row.id
      this.pathId = row.pathId
      this.dictName = row?.content
      let data = {
        parentId: row.id,
        langCode: this.languages.length > 0 ? this.currentLang : this.$lang
        // page: 1,
        // size: 99999
      }
      this.getDicDetailData(data)
    },
    //新增、编辑字典详情数据后更新字典详情列表
    updateDicDetail() {
      this.detailLoading = true
      let data = {
        parentId: this.dictionaryId,
        langCode: this.languages.length > 0 ? this.currentLang : this.$lang
      }
      this.getDicDetailData(data)
    },
    //获取字典详情数据
    getDicDetailData(data) {
      getDicDetail(data)
        .then((res) => {
          this.detailLoading = false
          if (res.status) {
            this.detailTableData = res.data ? res.data : []
          }
        })
        .catch(() => {
          this.detailTableData = []
          this.detailLoading = false
        })
    },
    //打开新增字典弹窗
    add() {
      this.dialogType = 'add'
      this.dicData = {
        langCode: this.$lang
      }
      this.dialogVisible = true
    },
    /**
     * @description: 编辑字典
     * @param {row} 被编辑行数据
     */
    edit(row) {
      this.dialogType = 'edit'
      this.dicData = {}
      getAllDicDetail({
        dictionaryId: row.id,
        langCode: ''
      }).then((res) => {
        res.data.forEach((item) => {
          if (item.content) {
            this.$set(this.dicData, item.langCode, item.content)
            this.$set(this.dicData, 'code', row.code)
            this.$set(this.dicData, 'id', row.id)
            this.$set(this.dicData, 'pathId', row.pathId)
            this.dialogVisible = true
          }
        })
      })
      // this.dicData = Object.assign(row, {
      //   langCode: this.$lang
      // })
      this.dialogVisible = true
    },
    //获取字典模块类型
    getModuleType() {
      getLangDicDetail({
        code: 'modules',
        langCode: this.languages.length > 0 ? this.currentLang : this.$lang
      }).then((res) => {
        if (res.data.modules) {
          res.data.modules.forEach((item) => {
            this.selectList.push({
              label: item[this.$lang],
              value: item.code
            })
          })
          this.currentType = this.selectList[0].value
          this.getDefaultData()
        }
      })
    },
    //初始化列表数据
    initData() {
      //加载左侧列表（根节点）,其中$lang为系统当前语种,currentLang为字典详情表表头中所选语种
      this.currentLang = this.$lang
      let data = {
        serviceType: 0,
        langCode: this.currentLang,
        code: this.searchValue,
        page: this.currentPage,
        size: this.pageSize
      }
      this.loading = true
      getDic(data)
        .then((res) => {
          if (res.status) {
            this.loading = false
            //获取左侧根节点列表
            this.tableData = res.data.list
            this.total = res.data.total
            //如果左侧根节点列表有值，渲染第一个字典详情
            if (res.data.list[0]) {
              this.dictName = res.data.list[0]?.content //第一个字典名称赋值
              this.dictionaryId = res.data.list[0].id //第一个字典id赋值
              this.pathId = res.data.list[0].pathId //第一个字典pathId赋值
              let data = {
                parentId: this.dictionaryId,
                langCode:
                  this.languages.length > 0 ? this.currentLang : this.$lang
              }
              this.getDicDetailData(data) //查询第一个字典详情
            } else {
              this.detailLoading = false
            }
          } else {
            this.detailLoading = false
          }
        })
        .catch((err) => {
          this.loading = false
          this.tableData = []
          this.total = 0
        })
      //await this.getModuleType()
      //this.getDefaultData()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .fks-table th > .cell .fks-input--small .fks-input__inner {
  border: none;
  text-align: center;
  background-color: transparent;
}

::v-deep .fks-select .fks-input .fks-select__caret {
  margin-top: -0.5px;
}

::v-deep .fks-table .fks-input--suffix .fks-input__inner {
  padding-left: 30px !important;
}

.dic-detail-box {
  height: 100%;
  background-color: #fff;
}
</style>